package com.situ.tos2024.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.filter.PropertyPreFilter;
import com.github.pagehelper.PageInfo;
import com.situ.tos2024.model.Category;
import com.situ.tos2024.service.CategoryService;
import com.situ.tos2024.util.JsonResult;
import com.situ.tos2024.util.PaginateInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能：用户微服务接口
 *
 * @author 千堆雪
 * @version 1.0.0
 * @since 2024/3/22
 * <p>
 * created by 千堆雪 on 2024/3/22 11:13, last modified by 千堆雪 on 2024/3/22 11:13
 */
@RestController
@RequestMapping(value = "/api/v1/categories", produces = "application/json")
public class CategoryApi {
    private final CategoryService categoryService;

    public CategoryApi(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 查询所有一级分类
     *
     * @return 所有一级分类
     */
    @GetMapping({"/{p}/{l}", "/{p}", ""})
    public String findAll(Category search,
                          @PathVariable(required = false) Integer p,
                          @PathVariable(required = false) Integer l,
                          @RequestParam(defaultValue = "1", name = "page") Integer pageNo,
                          @RequestParam(defaultValue = "20", name = "limit") Integer pageSize,
                          @RequestParam(defaultValue = "list") String format) {
        if (p != null) {
            pageNo = p;
        }
        if (l != null) {
            pageSize = l;
        }

        //创建一个分页对象
        PaginateInfo pi = PaginateInfo.of(pageNo, pageSize);

        //分页查询类别，延迟数据加载，不立即加载关联数据
        List<Category> categories = categoryService.findAll(pi, search);

        //PageHelper的分页对象
        PageInfo<?> pif = pi.getPageInfo();
        JsonResult result = JsonResult.success(pif.getTotal(), categories);

        String json = null;
        if ("tree".equals(format)) {//以树型数据展示
            json = JSON.toJSONString(result);
        } else {//以列表数据展示，不递归查询children
            //使用过滤器，忽略对children的序列化操作
            PropertyPreFilter filter = (writer, source, name) -> !(source instanceof Category) || !"children".equals(name);
            json = JSON.toJSONString(result, filter);
        }
        return json;
    }
}
